package hdwallet

import (
	"MPCBot/global"
	"os"

	cosmoshd "github.com/cosmos/cosmos-sdk/crypto/hd"
	"github.com/cosmos/cosmos-sdk/crypto/keyring"
	"github.com/evmos/ethermint/crypto/hd"
)

func keyringSetup(keyStorePath string, algo string) (keyring.Keyring, keyring.SignatureAlgo) {
	var kr keyring.Keyring
	var err error
	var algorithm keyring.SignatureAlgo

	if algo == "eth_secp256k1" {
		kr, err = keyring.New(
			"gw",
			keyring.BackendMemory,
			keyStorePath,
			os.Stdin,
			hd.EthSecp256k1Option(),
		)
		if err != nil {
			global.Log.Error("====>  Testhermit error： %s", err.Error())
		}

		algorithm = hd.EthSecp256k1
	} else {
		kr, err = keyring.New(
			"gw",
			keyring.BackendMemory,
			keyStorePath,
			os.Stdin,
		)
		if err != nil {
			global.Log.Error("====>  Testhermit error： %s", err.Error())
		}

		algorithm = cosmoshd.Secp256k1
	}

	return kr, algorithm
}

func UserNewKey(mnemonic string, keyStorePath string, keyOwnerName string, keyOwnerPw string, fullFundraiserPath string, selectAlgorithm string) (keyring.Keyring, keyring.Info, string, string) {
	if mnemonic == "" {
		return nil, nil, "redirect", ""
	}

	kr, algorithm := keyringSetup(keyStorePath, selectAlgorithm)

	info, err := kr.NewAccount(
		keyOwnerName,
		mnemonic,
		keyring.DefaultBIP39Passphrase,
		fullFundraiserPath,
		algorithm,
	)
	if err != nil {
		global.Log.Error("====>  Testhermit error： %s", err.Error())
		return nil, nil, "redirect", ""
	}

	priv, err := kr.ExportPrivKeyArmor(keyOwnerName, keyOwnerPw)
	if err != nil {
		global.Log.Error("====>  Testhermit error： %s", err.Error())
		return nil, nil, "redirect", ""
	}

	return kr, info, "normal", priv
}
